#!/usr/bin/python

import commonLib
import pickle
import sys
import optimizeLib
#This script is going to be very basic : no restore if it crashes
loadingAddress = commonLib.getOptions()['loadingAddress']

#We just open the deltaTable
f = open("./NodeCollectionWithDeltas",'r')
content =f.readlines()
f.close()

# Put everything in a single string so we can load it with pickle
contentString = ""
for line in content:
	contentString+=line

NodeCollection = pickle.loads(contentString)

mySerialPortInterface = commonLib.serialPortInterface(int(sys.argv[1]))

#We have the NodeCollection, we're now going to modify the value of limit in
#the kernel.

bootTimeArray = [] #To record the time it takes to boot depending on many time it takes to boot

lowerBound = optimizeLib.findMaxDelta(NodeCollection)
upperBound = optimizeLib.sumAllDeltas(NodeCollection)
step = (upperBound - lowerBound)/100

deltaTable = optimizeLib.generateDeltaTable(NodeCollection)

for i in range(0,100):
	commonLib.generateKernelCode("PARALLEL", "YES", deltaTable, lowerBound+i*step)
	command = "net init;load -b tftp://"+commonLib.getHostIP()+"/vmlinux.bin "+loadingAddress+";go\n" 
	commonLib.compileKernel()
	print command
	mySerialPortInterface.writeCommand(command)
	ret = mySerialPortInterface.analyzeInputStream('getBootTime')
	bootTimeArray.append(ret)
	optimizeLib.saveStatus(ret,i,mySerialPortInterface)

minIndex = optimizeLib.getIndexOfMinOf(bootTimeArray)

#Now we have the best limit we can patch the kernel and we're done!!
commonLib.generateKernelCode("PARALLEL","NO", deltaTable, lowerBound+minIndex*step)
commonLib.compileKernel()

